from robot.robot import *
import time

class Get_info(Login):
    def __init__(self, sid, pwd, url='http://61.183.22.151:8080/'):
        self.base_url = url
        self.key_url = parse.urljoin(url, '/jwglxt/xtgl/login_getPublicKey.html')
        self.login_url = parse.urljoin(url, '/jwglxt/xtgl/login_slogin.html')
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Referer': self.login_url}
        self.sess = requests.session()
        self.cookies_str = ''
        self.sid = sid
        self.pwd = pwd
        self.login(sid, pwd)
        self.cookies = self.cookies
    def get_person_info(self):
        '''获取个人信息'''
        url = parse.urljoin(self.base_url, '/jwglxt/xsxxxggl/xsxxwh_cxCkDgxsxx.html?gnmkdm=N100801')
        result = requests.get(url, headers=self.headers, cookies=self.cookies)
        json_result = result.json()
        self.person_data = {
            '年级代码Id':json_result['njdm_id'],
            '是否报道': json_result['bdzcbj'],
            '班级': json_result['bh_id'],
            '姓名': json_result['xm'],
            '电子邮箱':json_result['dzyx'],
            'has_xszp': json_result['has_xszp'],
            'jdNum': json_result['jdNum'],
            '学院': json_result['jg_id'],
            '家庭地址': json_result['jtdz'],
            '考生号': json_result['ksh'],
            '民族': json_result['mzm'],
            '培养层次': json_result['pyccdm'],
            'pyfaxx_id': json_result['pyfaxx_id'],
            '是否在校': json_result['sfzx'],
            '联系号码': json_result['sjhm'],
            '性别': json_result['xbm'],
            '学号': json_result['xh'],
            '学号id': json_result['xh_id'],
            '状态': json_result['xjztdm'],
            'xlccdm': json_result['xlccdm'],
            '学年': json_result['xnm'],
            '学年名称': json_result['xnmc'],
            'xqm': json_result['xqm'],
            '学期': json_result['xqmc'],
            '学制': json_result['xz'],
            '证件类型':json_result['zjlxm'],
            '证件号码': json_result['zjhm'],
            '专业': json_result['zyh_id'],
            '政治面貌': json_result['zzmmm']
        }
        self.year=self.person_data['学年']
        self.name=self.person_data['姓名']
        return self.person_data
    def get_message_info(self):
        """获取消息"""
        url = parse.urljoin(self.base_url, '/jwglxt/xtgl/index_cxDbsy.html?doType=query')
        data = {
            'sfyy': '0',  # 是否已阅，未阅未1，已阅为2
            'flag': '1',
            '_search': 'false',
            'nd': int(time.time() * 1000),
            'queryModel.showCount': '1000',  # 最多条数
            'queryModel.currentPage': '1',  # 当前页数
            'queryModel.sortName': 'cjsj',
            'queryModel.sortOrder': 'desc',  # 时间倒序, asc正序
            'time': '0'
        }
        res = requests.post(url, headers=self.headers, data=data, cookies=self.cookies)
        jres = res.json()
        res_list = [{'message': i['xxnr'], 'time': i['cjsj']} for i in jres['items']]
        '''返回结果：message：消息
                   time:消息时间             
        '''
        return res_list
    def get_grade_info(self, year='', term='all'):
        """获取成绩"""
        url = parse.urljoin(self.base_url, '/jwglxt/cjcx/cjcx_cxDgXscj.html?doType=query&gnmkdm=N305005')
        if term == '1' or term=='一':  # 修改检测学期
            term = '3'
        elif term == '2' or term=='二':
            term = '12'
        elif term == '0' or term=='all':
            term = ''
        else:
            print('Please enter the correct term value！！！ ("0" or "1" or "2")')
            return {}
        if year=='':
            year=self.year
        data = {
            'xnm': year,  # 学年数
            'xqm': term,  # 学期数，第一学期为3，第二学期为12, 整个学年为空''
            '_search': 'false',
            'nd': int(time.time()*1000),
            'queryModel.showCount': '100',  # 每页最多条数
            'queryModel.currentPage': '1',
            'queryModel.sortName': '',
            'queryModel.sortOrder': 'asc',
            'time': '0'  # 查询次数
        }
        result = requests.post(url, headers=self.headers, data=data, cookies=self.cookies)
        json_result = result.json()
        if json_result.get('items'):  # 防止数据出错items为空
            grade=[{
                '课程名称':item['kcmc'],
                '成绩': int(item['cj']),
                '学分': item['xf'],
                '绩点': item['jd'],
                '学分绩点': item['xfjd'],
                '成绩性质': item['ksxz'],
                '是否作废': item['cjsfzf'],
                '是否学位课程': item['sfxwkc'],
                '考核学年':item['xnm'],
                '考核学期':item['xqmmc'],
                '课程代码':item['kch'],
                '课程类别':item['kclbmc'],
                '课程标记':item['kcbj'],
                '考试班级':item['bh'],
                '授课老师':item['jsxm'],
              #  '考核方式':item['khfsmc'],
                '开课单位':item['jgmc'],
                '考试年级':item['njmc'],
                '统计人姓名':item['tjrxm'],
                '统计时间':item['tjsj']
            } for item in json_result['items']]
            return grade
        else:
            return {}

    def get_schedule_info(self, year='', term='1'):
        """获取课程表信息"""
        url = parse.urljoin(self.base_url, '/jwglxt/kbcx/xskbcx_cxXsKb.html?gnmkdm=N2151')
        if term == '1' or term=='一':  # 修改检测学期
            term = '3'
        elif term == '2' or term=='二':
            term = '12'
        else:
            print('Please enter the correct term value！！！ ("1" or "2")')
            return {}
        if year=='':
            year=self.year
        data = {
            'xnm': year,
            'xqm': term
        }
        result = requests.post(url, headers=self.headers, data=data, cookies=self.cookies)
        json_result=result.json()
        list1=json_result['kbList']
        data=[{
            '课程名称':row['kcmc'],
            '老师':row['xm'],
            '上课地点':row['cdmc'],
            '课程类别':row['kclb'],
            '课程学时':row['kcxszc'],
            '考核方式':row['khfsmc'],
            '开课学年':row['xnm'],
            '开课周':row['zcd'],
            '开课周列表':self.split_zcd(row['zcd']),
            '开课日':row['xqjmc'],
            '开课日数字':row['xqj'],
            '课程学分':row['xf'],
            '开课节次':row['jc'],
            '节次':list(range(int(row['jcor'].split('-')[0]),int(row['jcor'].split('-')[1])+1))
        } for row in list1]
        return data
    @classmethod
    def split_zcd(cls,zcd):
        '''转化开课周成列表'''
        week = []
        zcds = zcd.split(',')
        for one in zcds:
            a = one.strip('周')
            b = a.split('-')
            try:
                c = list(range(int(b[0]), int(b[1]) + 1))
            except:
                c=[int(b[0])]
            week=week+c
        return week
    #
    def get_class(self):

        url = parse.urljoin(self.base_url, '/jwglxt/xsxk/zzxkyzbjk_cxJxbWithKchZzxkYzb.html?gnmkdm=N253512&su='+self.sid)
        url2=parse.urljoin(self.base_url, '/jwglxt/xsxk/zzxkyzb_cxZzxkYzbPartDisplay.html?gnmkdm=N253512&su='+self.sid)
        url3=parse.urljoin(self.base_url, 'jwglxt/xsxk/zzxkyzbjk_xkBcZyZzxkYzb.html?gnmkdm=N253512&su='+self.sid)
        data={
            'rwlx': 3,
            'xkly': 0,
            'bklx_id': 'AA4E9A53CE88F9EFE05515AE61506085',
            'xqh_id': '00001',#学期号id
            'jg_id': '00012',
            'zyh_id': '17DL1',
            'zyfx_id': 'wfx',
            'njdm_id': self.person_data['年级代码Id'],
            'bh_id': 'AA5DEE69D31D0EBFE05515AE61506085',
            'xbm': 1,
            'xslbdm': 'wlb',
            'ccdm': 3,
            'xsbj': '4294967296',
            'sfkknj': 0,
            'sfkkzy': 0,
            'sfznkx': 0,
            'zdkxms': 0,
            'sfkxq': 0,
            'sfkcfx': 0,
            'kkbk': 0,
            'kkbkdj': 0,
            'sfkgbcx': 0,
            'sfrxtgkcxd': 0,
            'tykczgxdcs': 0,
            'xkxnm': self.person_data['学年'],
            'xkxqm': self.person_data['xqm'],
            'rlkz': 0,
            'kklxdm': '06',
            'kch_id': 'CC58A78330C243C1AA6534EE6D1E6354',
            'xkkz_id': 'BC66C09EF06B1C21E05515AE61506085',
            'cxbj': 0,
            'fxbj': 0,
            'xkzgbj': 0,
            'kspage': 1,
            'jspage': 10,
            'jxbzb':''
        }
        result = requests.post(url, headers=self.headers, cookies=self.cookies,data=data)
        json_datas=result.json()
        result2=requests.post(url2, headers=self.headers, cookies=self.cookies,data=data)
        json_result2=result2.json()
        json_datas2=json_result2['tmpList']
        j=0
        for json_data2 in json_datas2:
            print(str(j)+'、'+str(json_data2['jxbmc'])+'   '+json_data2['yxzrs']+'/'+json_datas[j]['jxbrl'])
            if json_data2['yxzrs']==json_datas[j]['jxbrl']:
                print('已满')
            j+=1
        success=0
        while success==0:
            i=int(input("请输入你要选择的学科:"))
            data2={
                'jxb_ids':json_datas[i]['do_jxb_id'],
                'kch_id':json_datas2[i]['kch_id'],
                'kcmc':'('+json_datas2[i]['kch']+')'+json_datas2[i]['kcmc']+' - '+json_datas2[i]['xf']+'学分',
                'rwlx':data['rwlx'],
                'rlkz':data['rlkz'],
                'rlzlkz':1,
                'sxbj':1,
                'xxkbj':1,
                'qz':0,
                'cxbj':json_datas2[i]['cxbj'],
                #'xkkz_id':data['xkkz_id'],
                'njdm_id':data['njdm_id'],
                'zyh_id':data['zyh_id'],
                'kklxdm':data['kklxdm'],
                'xklc':1,
                'xkxnm':data['xkxnm'],
                'xkxqm':data['xkxqm']
            }
            result3 = requests.post(url3, headers=self.headers, cookies=self.cookies, data=data2)
            json_datas3 = result3.json()
            if json_datas3['flag']=='1':
                print('选课成功')
                success=1
            else:
                print(json_datas3['msg'])

